package sit.engreal.leetcode.problems800;

/**
 * <a href="https://leetcode.cn/problems/binary-search/">704. 二分查找</a>
 */
public class LeetCode704 {
    public static void main(String[] args) {
        class Solution {
            public int search(int[] nums, int target) {
                int left = 0;
                int right = nums.length;
                while (left < right) {
                    int i = (left + right) / 2;
                    if (nums[i] < target) {
                        left = i + 1;
                    } else if (nums[i] > target) {
                        right = i;
                    } else {
                        return i;
                    }
                }
                return -1;
            }
        }

        final Solution solution = new Solution();
        assert 4 == solution.search(new int[]{-1, 0, 3, 5, 9, 12}, 9);
        assert -1 == solution.search(new int[]{-1, 0, 3, 5, 9, 12}, 2);
    }
}

